package com.yygo.webapp.controller.loanrequest;

import com.yygo.Constants;
import com.yygo.model.LoanRequest;
import com.yygo.model.User;
import com.yygo.service.LoanRequestManager;
import com.yygo.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Date;

/**
 * Created by xixin on 10/9/2015.
 */
@Controller
@RequestMapping("/batchLoaned")
public class BatchLoanedController extends BaseLoanRequestFormController {
  @Autowired
  private LoanRequestManager loanRequestManager;

  @Autowired
  private UserManager userManager;

  @RequestMapping(method = RequestMethod.GET)
  public String batchLoaned(Model model, HttpServletRequest request, @RequestParam(required = true, value = "requestIds") Long[] selectedIds, @RequestParam(required = true, value = "date") Date date,  Principal principal) throws IllegalAccessException {
    User loginUser = userManager.getUserByUsername(principal.getName());
    if (!loginUser.hasRole(Constants.Bank_USER_ROLE)) {
      throw new AccessDeniedException("You have no right to batch loaned requests");
    }

    for (Long id : selectedIds) {
      LoanRequest loanRequest = loanRequestManager.loadWholeLoanRequest(id);
      handleAction(ACTION_bankLoaned, loanRequest, request.getLocale(), loginUser);
      loanRequest.setLoanDate(date);
      loanRequestManager.saveLoanRequest(loanRequest);
    }

    return "redirect:/myloanrequests?phase=bank_pending_loan";
  }
}
